package com.boot.test;

import io.reactivex.Observable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observables.ConnectableObservable;
import io.reactivex.schedulers.Schedulers;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class RxJavaHotAndColdObservable {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch finish = new CountDownLatch(2);
        Consumer<Long> subscriber1 = l -> System.out.println("subscriber1: " + l);
        Consumer<Long> subscriber2 = l -> System.out.println("subscriber2: " + l);
        ConnectableObservable<Long> observable = Observable.interval(1, TimeUnit.SECONDS)
                                     .take(6).observeOn(Schedulers.computation()).publish();
        observable.connect();
        Observable<Long> coldObservable = observable.refCount();
        Disposable d1 = observable.subscribe(subscriber1, System.err::println, () -> finish.countDown());
        Disposable d2 = observable.delaySubscription(2, TimeUnit.SECONDS)
                                    .subscribe(subscriber2, System.err::println, () -> finish.countDown());
        Thread.sleep(2000L);
//        d1.dispose();
//        d2.dispose();
        System.out.println("-------------");
        coldObservable.subscribe(subscriber1, System.err::println, () -> finish.countDown());
        coldObservable.subscribe(subscriber2, System.err::println, () -> finish.countDown());
        finish.await();
    }

}
